from utils import log_info, log_exception
from typing import List, Optional
from .base_dao import BaseDAO
from models.error_question import ErrorQuestion


class ErrorQuestionDAO(BaseDAO[ErrorQuestion]):
    """错题表数据访问对象"""

    def __init__(self):
        """
        初始化ErrorQuestionDAO
        """
        super().__init__(ErrorQuestion)

    def _get_table_name(self) -> str:
        """获取表名"""
        return "error_questions"

    def _get_primary_key(self) -> str:
        """获取主键字段名"""
        return "id"

    def get_by_user_id(self, user_id: int) -> List[ErrorQuestion]:
        """
        根据用户ID获取所有错题
        :param user_id: 用户ID
        :return: 错题实体对象列表
        """
        sql = "SELECT * FROM error_questions WHERE user_id = ?"
        params = (user_id,)
        return self._execute_query(sql, params)



    def get_by_user_and_question(self, user_id: int, question_id: int) -> Optional[ErrorQuestion]:
        """
        根据用户ID和题目ID获取错题
        :param user_id: 用户ID
        :param question_id: 题目ID
        :return: 错题实体对象，如果不存在返回None
        """
        sql = "SELECT * FROM error_questions WHERE user_id = ? AND question_id = ?"
        params = (user_id, question_id)
        results = self._execute_query(sql, params)
        return results[0] if results else None

    def get_by_user_question_and_category(self, user_id: int, question_id: int, category: str) -> Optional[ErrorQuestion]:
        """
        根据用户ID、题目ID和类别获取错题
        :param user_id: 用户ID
        :param question_id: 题目ID
        :param category: 类别
        :return: 错题实体对象，如果不存在返回None
        """
        sql = "SELECT * FROM error_questions WHERE user_id = ? AND question_id = ? AND category = ?"
        params = (user_id, question_id, category)
        results = self._execute_query(sql, params)
        return results[0] if results else None

    def get_by_user_and_category(self, user_id: int, category: str) -> List[ErrorQuestion]:
        """
        根据用户ID和类别获取错题
        :param user_id: 用户ID
        :param category: 类别
        :return: 错题实体对象列表
        """
        sql = "SELECT * FROM error_questions WHERE user_id = ? AND category = ?"
        params = (user_id, category)
        return self._execute_query(sql, params)

    def get_error_questions_with_details(self, user_id: int, category: str) -> List[ErrorQuestion]:
        """
        根据用户ID和类别获取错题，并关联查询题目详情
        :param user_id: 用户ID
        :param category: 类别
        :return: 关联后的错题对象列表
        """
        sql = """
        SELECT eq.*, q.type, q.Q, q.A, q.B, q.C, q.D, q.T, q.F, q.LA, q.LB, q.LC, q.I, q.J, q.P
        FROM error_questions eq
        JOIN questions q ON eq.question_id = q.id
        WHERE eq.user_id = ? AND eq.category = ?
        """
        params = (user_id, category)
        return self._execute_query(sql, params)

    def delete_by_user_and_question(self, user_id: int, question_id: int) -> bool:
        """
        根据用户ID和题目ID删除错题
        :param user_id: 用户ID
        :param question_id: 题目ID
        :return: 删除成功返回True，否则返回False
        """
        try:
            sql = "DELETE FROM error_questions WHERE user_id = ? AND question_id = ?"
            params = (user_id, question_id)
            conn = self._get_connection()
            if not conn:
                return False
            cursor = conn.cursor()
            cursor.execute(sql, params)
            conn.commit()
            if cursor.rowcount > 0:
                log_debug(f"删除用户{user_id}的题目{question_id}的错题成功")
                return True
            log_debug(f"未找到用户{user_id}的题目{question_id}的错题记录")
            return False
        except Exception as e:
            log_exception(f"删除错题失败: {str(e)}")
            return False
        finally:
            if 'conn' in locals():
                self.db_pool.release_connection(conn)